<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Admin;

use App\Middleware\JwtMiddleware;
use App\Middleware\ManagerRights;
use App\Model\Banner;
use App\Model\User;
use App\Resource\UserCollection;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Validation\Rule;

#[Controller]
class UserController
{
    #[Inject]
    protected ValidatorFactoryInterface $validationFactory;

    #[Inject]
    protected RequestInterface $request;

    #[Middleware(JwtMiddleware::class)]
    #[Middleware(ManagerRights::class)]
    #[RequestMapping(path: "", methods: "get")]
    /**
     * 列表
     * @return false|string
     */
    public function list()
    {
        $list = User::query();
        if ($status = $this->request->input('status')) {
            $list->where('status', $status);
        }

        if ($keyword = $this->request->input('keyword')) {
            $list->keyword($keyword);
        }
        $list->with(['header', 'enterprise']);

        $list = $list->paginate((int)$this->request->input('page_num', 15));
        $data = [
            'list' => (new UserCollection($list))->toListApi(),
            'count' => $list->total(),
            'count_page' => $list->lastPage(),
            'page_num' => $list->perPage(),
        ];

        return self::jsonResponse(200, 'success', $data);
    }

    #[Middleware(JwtMiddleware::class)]
    #[RequestMapping(path: "detail", methods: "get")]
    public function detail()
    {
        $id = $this->request->input('id');
        $user = User::getById($id);
        if (!$user) {
            return self::jsonResponse(404, '数据不存在');
        }

        return self::jsonResponse(200, 'success', $user->toApi());
    }

    #[Middleware(JwtMiddleware::class)]
    #[Middleware(ManagerRights::class)]
    #[RequestMapping(path: "edit", methods: "post")]
    /**
     * 编辑
     * @return false|string
     */
    public function edit()
    {
        $id = $this->request->input('id');
        $user = User::getById($id);
        if (!$user) {
            return self::jsonResponse(404, '数据不存在');
        }

        $data = $this->validationFactory->make(
            $this->request->all(),
            [
                'nickname' => 'required',
                'mobile' => [
                    'required',
                    Rule::unique('user')->where(function ($q) use ($id) {
                        $q->whereNull('delete_time')->where('id', '!=', $id);
                    }),
                ],
                'header_img_id' => '',
            ],
            [
                'nickname.required' => '请填写用户昵称',
                'mobile.required' => '请填写用户手机号',
                'mobile.unique' => '手机号被占用',
            ]
        );

        if ($data->fails()) {
            return self::jsonResponse(422, $data->errors()->first());
        }

        $data = $data->validated();
        $user->fill($data);
        $user->save();

        return self::jsonResponse();
    }

    #[Middleware(JwtMiddleware::class)]
    #[Middleware(ManagerRights::class)]
    #[RequestMapping(path: "handle", methods: "post")]
    /**
     * 启用/禁用
     * @return false|string
     */
    public function handle()
    {
        $id = $this->request->input('id');
        $user = User::getById($id);
        if (!$user) {
            return self::jsonResponse(404, '数据不存在');
        }

        $user->handle();
        $user->save();

        return self::jsonResponse();
    }

    #[Middleware(JwtMiddleware::class)]
    #[Middleware(ManagerRights::class)]
    #[RequestMapping(path: "delete", methods: "delete")]
    /**
     * 删除
     * @return false|string
     * @throws \Exception
     */
    public function delete()
    {
        $id = $this->request->input('id');
        $user = User::getById($id);
        if (!$user) {
            return self::jsonResponse(404, '数据不存在');
        }

        $user->delete();

        return self::jsonResponse();
    }

    /**
     * 返回统一json
     * @param int $status
     * @param $message
     * @param $data
     * @param $headerStatus
     * @return false|string
     */
    public static function jsonResponse(int $status = 200, $message = 'success', $data = null, $headerStatus = 200)
    {
        if (is_array($message)) {
            $data = $message;
            $message = 'success';
        }
        if (empty($data)) {
            $data = new class {
            };
        }

        return json_encode(['status' => $status, 'message' => $message, 'data' => $data]);

//        return response()->json(
//            ['status' => $status, 'message' => $message, 'data' => $data],
//            $headerStatus,
//            [],
//            JSON_UNESCAPED_UNICODE
//        );
    }
}
